from django import template

register = template.Library()


@register.filter(name="get_item")
def get_item(obj, key):
    """
    读取字典/对象的字段值：
    - 若 obj 为 dict，返回 obj.get(key, "")
    - 否则尝试 getattr(obj, key, "")
    - 任何异常返回空字符串，避免模板报错
    """
    try:
        if obj is None or key is None:
            return ""
        if isinstance(obj, dict):
            return obj.get(key, "")
        return getattr(obj, key, "")
    except Exception:
        return ""
@register.filter
def attr(obj, attribute):
    """获取对象的属性"""
    return getattr(obj, attribute, None)